package com.xmb.wechat.view.wechat.money;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;

import com.xmb.wechat.R;
import com.xmb.wechat.R2;
import com.xmb.wechat.application.WechatStartApplication;
import com.xmb.wechat.base.BaseActivity;
import com.xmb.wechat.bean.BankCardBean;
import com.xmb.wechat.definterface.onBankCardChooseCallBack;
import com.xmb.wechat.delegate.BankCardDelegate;

import java.util.List;

import butterknife.OnClick;
import io.objectbox.Box;

/**
 * @Author lijiangop
 * @CreateTime 2020/4/16 17:54
 */
public class WechatFundBankCardActivity extends BaseActivity {

    private static final int REQUEST_CODE_ADD = 107;

    private BankCardDelegate  mDelegate;
    private Box<BankCardBean> mBox;

    public WechatFundBankCardActivity() {
        super(R.layout.activity_fund_bank_card);
    }

    public static void startforResult(Activity activity, int requestCode) {
        Intent intent = new Intent(activity, WechatFundBankCardActivity.class);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void initView() {
        mDelegate = new BankCardDelegate(this, new onBankCardChooseCallBack() {
            @Override
            public void onClick(BankCardBean bankCardBean) {
                Intent intent = new Intent();
                intent.putExtra("result", bankCardBean);
                setResult(RESULT_OK, intent);
                finish();
            }

            @Override
            public void onLongClick(BankCardBean bankCardBean) {
                new AlertDialog.Builder(WechatFundBankCardActivity.this).setItems(new String[]{"删除"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mBox.remove(bankCardBean);
                        refresh();
                    }
                }).setNegativeButton("取消", null).show();
            }
        });
        refresh();
    }

    private void refresh() {
        if (mBox == null)
            mBox = WechatStartApplication.getBoxStore(this).boxFor(BankCardBean.class);
        List<BankCardBean> bankCardBeans = mBox.query().build().find();
        if (bankCardBeans.size() > 0) {
            mDelegate.clearData();
            mDelegate.addData(bankCardBeans);
        }
    }

    @OnClick(R2.id.btn_add)
    public void onViewClicked() {
        WechatFundBankCardAddActivity.startForResult(WechatFundBankCardActivity.this, REQUEST_CODE_ADD);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_ADD) {
            refresh();
        }
    }
}
